/*
 * @Author: lande 615542329@qq.com
 * @Date: 2023-02-15 10:21:48
 * @LastEditors: lande 615542329@qq.com
 * @LastEditTime: 2023-02-21 13:51:48
 * @FilePath: \ScriptProjects\Tiktok_Project\tk_register.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

const Diy = require("./diy_module.js");
const { clickWidget, clickWidgetEx, widgetBounds, findWidget, sleepEx, sml_move, smlMoveUp, getLevel, clearApp, closeApp } = Diy;
function VpnClass(user, password, port) {
    this.vpnUser = user;
    this.password = password;
    this.port = port;

    this.launchV2ranNG = function () {
        $app.launch('com.v2ray.ang');
        sleepEx(2000);
        while (!packageName('com.v2ray.ang').findOnce()) {


        }
    }
}

/**
 * @description: TK类
 * @return {*}
 */
function TkClass(emailAddress, password, nickName) {
    this.firstLaunch = true;
    this.status = "launch";
    this.runStatus = true;
    this.emailAddress = emailAddress;
    this.password = password;
    this.nickName = nickName;
    this.main = function () {
        while (this.runStatus) {
            switch (this.status) {
                case "launch":
                    this.launch();
                    break;
                case "register":
                    this.registerProcess();
                    break
                case "finish":
                    home();
                    sleepEx(2000);
                    console.log("完成-注册任务");
                    return;
            }

            sleepEx(100);
        }
    }

    /**
     * @description: 更改手机参数
     * @return {*}
     */    
    this.changePhoneParam = function(){

    }

    /**
     * @description: 启动tk
     * @return {*}
     */
    this.launch = function () {
        if (this.firstLaunch) {
            console.log("首次启动");
            clearApp("com.ss.android.ugc.trill");
            $app.launch("com.ss.android.ugc.trill");
            sleepEx(3000);
            this.firstLaunch = false;
            console.log("完成-启动");
        }
        clickWidget(findWidget({ text: "Agree and continue", id: "com.ss.android.ugc.trill:id/acj", className: "android.widget.TextView" }, "tic"));
        console.log("1");
        // clickWidget(id("com.ss.android.ugc.trill:id/text").className("android.widget.TextView").findOnce());
        if (findWidget({ text: "Choose your interests", id: "com.ss.android.ugc.trill:id/crj", className: "android.widget.TextView" }, "tic")) {
            console.log("找到-选择兴趣");
            let interestsList = id("com.ss.android.ugc.trill:id/text").className("android.widget.TextView").find();
            if (interestsList.nonEmpty()) {
                let index = 0;
                for (let i = 0; i < interestsList.lenght; i++) {
                    widgetBounds(interestsList[i]) && index++;

                }
                console.log("index: ", index);
                clickWidget(interestsList[random(0, index)]);
                sleepEx(2000);
            }
        }

        clickWidget(text("Next").id("com.ss.android.ugc.trill:id/bim").className("android.widget.TextView").enabled(true).findOnce());

        clickWidget(findWidget({ text: "Start watching", id: "com.ss.android.ugc.trill:id/hb8", className: "android.widget.TextView" }, "tic"));

        if (findWidget({ text: "Swipe up for more", id: "com.ss.android.ugc.trill:id/ix5", className: "android.widget.TextView" }, "tic")) {
            smlMoveUp();
        }

        if (findWidget({ text: "Home", className: "android.widget.TextView" }, "tc") || text("Don’t have an account? Sign up").id("com.ss.android.ugc.trill:id/e_f").className("android.widget.TextView").findOnce()) {
            this.status = "register";
            console.log("完成-启动tk");

        }


    }

    /**
     * @description: 注册流程
     * @return {*}
     */
    this.registerProcess = function () {
        // clickWidget(findWidget({ text: "Agree and continue", id: "com.ss.android.ugc.trill:id/acj", className: "android.widget.TextView" }, "tic"));


        // clickWidget(findWidget({ text: "Start watching", id: "com.ss.android.ugc.trill:id/hb8", className: "android.widget.TextView" }, "tic"));

        findWidget({ text: "Swipe up for more", id: "com.ss.android.ugc.trill:id/ix5", className: "android.widget.TextView" }, "tic") && smlMoveUp();

        clickWidget(findWidget({ text: "Profile", className: "android.widget.TextView" }, "tc"));

        clickWidget(findWidget({ text: "Sign up", id: "com.ss.android.ugc.trill:id/afy", className: "android.widget.TextView" }, "tic"));
        clickWidget(findWidget({ text: "Email", id: "android:id/text1", className: "android.widget.TextView" }, "tic"));

        clickWidget(findWidget({ text: "Don’t have an account? Sign up", id: "com.ss.android.ugc.trill:id/e_f", className: "android.widget.TextView" }, "tic")) && sleepEx(2000);

        // clickWidget(findWidget({text:"",id:"",className:""},"tic"));
        if (findWidget({ text: "Already have an account? Log in", id: "com.ss.android.ugc.trill:id/e_f", className: "android.widget.TextView" }, "tic")) {
            clickWidget(findWidget({ text: "Use phone or email", id: "com.ss.android.ugc.trill:id/ano", className: "android.widget.TextView" }, "tic"));
            sleepEx(2000);
        }

        let edit = findWidget({ text: "Email address", id: "com.ss.android.ugc.trill:id/d7p", className: "android.widget.EditText" }, "tic");
        if (edit) {
            console.log("this.emailAddress: ", this.emailAddress);
            edit.setText(this.emailAddress);
            sleepEx(1000);
            console.log("完成-设置邮箱");
        }

        clickWidget(text("Next").id("com.ss.android.ugc.trill:id/ec8").className("android.widget.TextView").enabled(true).findOnce());

        if(findWidget({text:"Too many attempts. Try again later.",id:"com.ss.android.ugc.trill:id/gdh",className:"android.widget.TextView"},"tic")){
            // 说明需要重新修改参数了，任务重新开始。
            this.status = "launch";
        }
        if (findWidget({ text: "When’s your birthday?", id: "com.ss.android.ugc.trill:id/nx", className: "android.widget.TextView" }, "tic")) {
            this.chooseBrithday();
            console.log("完成-选择生日");

        }
        clickWidget(findWidget({ text: "Next", id: "com.ss.android.ugc.trill:id/o7", className: "android.widget.TextView" }, "tic"));
        this.SliderVerificationCode();
        this.enterPassword();
        this.rotationVerificationCode();
        this.toHome();

    }

    /**
     * @description: 选择生日的日期
     * @return {*}
     */
    this.chooseBrithday = function () {
        let yearCount = random(19, 35);
        let monthCount = random(1, 8);
        let dateCount = random(1, 15);
        this.swipeBrithdayWidget(findWidget({ id: "com.ss.android.ugc.trill:id/em8", className: "android.view.View" }, "ic"), monthCount, "up");
        this.swipeBrithdayWidget(findWidget({ id: "com.ss.android.ugc.trill:id/b_p", className: "android.view.View" }, "ic"), dateCount, "up");
        this.swipeBrithdayWidget(findWidget({ id: "com.ss.android.ugc.trill:id/jmn", className: "android.view.View" }, "ic"), yearCount, "down");

    }

    /**
     * @description: 滑动选择对应的生日时间
     * @param {object} object 传入控件对象
     * @param {Number} swipeCount 滑动的次数
     * @param {Number} swipeDirection 滑动的方向
     * @return {*}
     */
    this.swipeBrithdayWidget = function (object, swipeCount, swipeDirection) {
        try {
            if (!object) {
                return;
            }
            let count = random(1, swipeCount, swipe);
            console.log(count);
            for (let i = 0; i < count; i++) {
                if (swipeDirection == "up") {

                    sml_move(object.bounds().centerX() - random(10, 15), object.bounds().bottom - random(15, 25), object.bounds().centerX() + random(10, 15), object.bounds().top + random(85, 90), random(300, 500));

                } else {
                    sml_move(object.bounds().centerX() - random(10, 15), object.bounds().top + random(15, 25), object.bounds().centerX() + random(10, 15), object.bounds().bottom - random(85, 90), random(300, 500));

                }
                sleepEx(300);
            }
        } catch (error) {
            console.log("选择生日日期报错：", error);
        }
    }

    /**
     * @description: 滑块处理
     * @return {*}
     */
    this.SliderVerificationCode = function () {
        let imgObj = Diy.getLevel(findWidget({ text: "Verify to continue:", className: "android.view.View" }, "tc"), 2);
        
        if (imgObj) {
            console.log("找到-滑块");
            while (findWidget({ text: "Loading...", className: "android.view.View" }, "ic")) {
                console.log("正在加载滑块图片。。。");
                sleepEx(2000);

            }
            let imgBig = images.captureScreen();
            sleepEx(500);
            let rect = widgetBounds(imgObj, "object");
            let img = images.clip(imgBig, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top - 50);
            const pathImg = "/sdcard/swipePic/1.png";
            files.remove(pathImg);
            sleepEx(100);
            files.ensureDir(pathImg);
            img.saveTo(pathImg);
            sleepEx(300);
            let pointWidth = this.tuLing("biyun001", "biyun001", "84292347", images.toBase64(images.read(pathImg), "png", 100));
            console.log("识别的缺口图片X：", pointWidth);
            let imgLittleObj = Diy.getLevel(findWidget({ text: "Verify to continue:", className: "android.view.View" }, "tc"), 4);
            if (imgLittleObj) {
                let ranNum = random(5, 10);
                let pointX1 = imgLittleObj.bounds().centerX() + ranNum;
                let pointX2 = imgObj.bounds().left + parseInt(pointWidth);   // + (imgLittleObj.bounds().left - imgObj.bounds().left - ranNum)

                console.log(pointX1, imgLittleObj.bounds().centerY() + random(1, 10), pointX2, imgLittleObj.bounds().centerY() + random(1, 10), random(500, 1000));
                sml_move(pointX1, imgLittleObj.bounds().centerY() + random(1, 10), pointX2, imgLittleObj.bounds().centerY() + random(1, 10), random(500, 1000));
                sleepEx(5000, 8000);
                console.log("完成-滑块打码");

            }
            while (!findWidget({ text: "Create password", id: "com.ss.android.ugc.trill:id/a3q", className: "android.widget.TextView" }, "tic")) {
                clickWidget(findWidget({ text: "Refresh", className: "android.view.View" }, "ic"))
                // 
                // text:Loading...  className:android.view.View 
                sleepEx(1000);
                while (findWidget({ text: "Loading...", className: "android.view.View" }, "ic")) {
                    console.log("正在加载滑块图片。。。");
                    sleepEx(2000);

                }
                this.SliderVerificationCode();
                sleepEx(2000);
            }
        }

    }
    /**
     * @description: 对接图灵打码
     * @param {String} userName 图灵打码账号
     * @param {String} passWord 图灵打码密码
     * @param {String} type 图灵打码模型ID
     * @param {String} imgBase64 图片的BASE64字符串
     * @return {Number} Number 成功返回坐标，识别返回-1
     */
    this.tuLing = function (userName, passWord, type, imgBase64) {
        try {
            const url = "http://www.tulingtech.xyz/tuling/predict";
            let res = http.postJson(url, {
                username: userName,
                password: passWord,
                b64: imgBase64,
                ID: type,
                version: "3.1.1"
            });
            let result = res.body.json();
            console.log(result);
            if (result.code == 1) {
                console.log("识别-图片成功");
                console.log(result.data);
                return result["data"]["滑块"]["X坐标值"];

            } else {
                console.log("识别-图片失败");
            }
        } catch (error) {
            console.log("识别-图片报错：", error);
        }
        return -1;
    }

    this.enterPassword = function () {
        let obj = findWidget({ text: "Enter password", id: "com.ss.android.ugc.trill:id/d7p", className: "android.widget.EditText" }, "tic");
        if (obj) {
            obj.setText(this.password);
            sleepEx(1000);
            clickWidget(findWidget({ text: "Next", id: "com.ss.android.ugc.trill:id/ec8", className: "android.widget.TextView" }, "tic"));
            sleepEx(3000);

        }
    }
    /**
     * @description: 双旋转验证码处理
     * @return {*}
     */
    this.rotationVerificationCode = function () {

    }


    /**
     * @description: 一直到注册完成
     * @return {*}
     */
    this.toHome = function () {
        let obj = findWidget({ text: "Add your nickname", id: "com.ss.android.ugc.trill:id/d7p", className: "android.widget.EditText" }, "tic");
        if (obj) {
            obj.setText(this.nickName);
            sleepEx(1000);
        }
        clickWidget(text("Confirm").id("com.ss.android.ugc.trill:id/ec8").className("android.widget.TextView").enabled(true).findOnce());
        clickWidget(findWidget({ text: "Don't allow", className: "android.widget.TextView" }, "tc"));
        if (findWidget({ text: "Home", className: "android.widget.TextView" }, "tc")) {
            this.status = "finish";
        }
    }
}


const TK = new TkClass("jeff@cuiqiu.com", "e81g1q2l8f7");
// Tk.launch();
// TK.registerProcess();
// TK.main();
// TK.chooseBrithday();

// console.log(text("Don’t have an account? Sign up").id("com.ss.android.ugc.trill:id/e_f").className("android.widget.TextView").findOnce());
// Diy.clearApp("com.ss.android.ugc.trill");
// let birthday = findWidget({id:"com.ss.android.ugc.trill:id/d7p",className:"android.widget.EditText"},"ic");
// if(birthday){
//     birthday.setText("June 18, 1996");
// }

// text = Let's go className = android.widget.TextView
// let month = findWidget({ id: "com.ss.android.ugc.trill:id/b_p", className: "android.view.View" }, "ic");
// if (month) {
//     console.log("111");
//     // month.scrollForward();
//     // month.scrollBackward();
//     // let rect = widgetBounds(month,"object");
//     console.log(month.bounds().centerX(), month.bounds().bottom, month.bounds().centerX(), month.bounds().top);
//     let count = random(1, 8);
//     console.log(count);
//     for (let i = 0; i < count; i++) {
//         sml_move(month.bounds().centerX(), month.bounds().bottom - 20, month.bounds().centerX(), month.bounds().top + 90, random(300, 400));
//         sleepEx(500, 700);
//     }
// }

threads.start(function () {
    if (!requestScreenCapture()) {
        console.info("申请截图权限失败!");
        exit();
    } else {
        // clickWidget();
        // 这里写自动开始截图的内容。
    }
});

TK.main();


